package com.xjc.agent.core.util;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.util.Iterator;
import java.util.List;

/**
 * @author: 谢君臣
 * @Date: 2023/1/8-15:08
 * @version: 1.0
 * @function:
 */
public class AgentUtil {
    public static String findAgentDirPath() {
        List<String> arguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
        Iterator<String> iterator = arguments.iterator();
        while (iterator.hasNext()) {
            String argument = iterator.next();
            if (argument.startsWith("-javaagent:") && argument.contains("agent")) {
                String path = argument.replaceFirst("-javaagent:", "").split("=")[0];
                return new File(path).getParent();
            }
        }
        return "";
    }
    public static String findAgentJarPath() {
        List<String> arguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
        Iterator<String> iterator = arguments.iterator();
        while (iterator.hasNext()) {
            String argument = iterator.next();
            if (argument.startsWith("-javaagent:") && argument.contains("agent-core")) {
                return argument.replaceFirst("-javaagent:", "").split("=")[0];
            }
        }
        return "";
    }
}
